<template>
  <div class="search-suggestion">
    <van-cell 
      v-for="(item,i) in suggetsionList"
      :key="i"
      @click="$emit('search-item', item)"
      icon="search">
      <span slot="title" v-html="handlerText(item)"></span>
    </van-cell>
  </div>
</template>

<script>
import {getSearchSuggestion} from '@/api/search'
import { debounce } from 'lodash'

export default {
  props: ['searchText'],
  watch: {
    searchText: {
      handler: debounce(function(newVal){
        this.getSuggerstionList(newVal)
      }, 1000),
      immediate: true
    }
  },
  data() {
    return {
      suggetsionList: []
    }
  },
  methods: {
    async getSuggerstionList(newVal) {
      try {
        const {data} = await getSearchSuggestion(newVal)

        this.suggetsionList = data.data.options
      }catch(err) {
        this.$toast('请求失败')
      }
    },
    handlerText(text) {
      let reg = new RegExp(this.searchText, 'ig')

      return text.replace(reg, `<span style="color: red">${this.searchText}</span>`)
    }
  }
}
</script>

<style lang="less" scoped>

</style>